/**
 * This file contains all the user routes
 */

const Router = require('restify-router').Router;
const { InternalServerError, BadRequestError } = require('restify-errors');
const validate = require('restify-api-validation');
const Joi = require('joi');
const _ = require('lodash');

const routerInstance = new Router();
const passport = require('../auth');

const axios = require('axios').default;
const rootUrl = 'http://localhost:3000/';

async function request(url, opts) {
  url = `${rootUrl}${url}`;
  // opts = Object.assign({
  //   timeout: [ '30s', '30s' ],
  //   dataType: 'json',
  // }, opts);
  //return this.ctx.curl(url, opts);
  return await axios({
    method: opts.method,
    url: url,
    data: opts.data,
    responseType: opts.contentType
  });
}

async function userRegister() {
  const params = {
    'username': "test1",
    'email': "test1@126.com",
    'password': '123456'
  }
  const result = await request('user/register', {
    method: 'post',
    data: params,
    contentType: 'json',
  });

  return result;
}

async function userLogin() {
  const params = {
    //'username': "test12",
    'email': "pritojs@gmail.com",
    'password': '12345'
  }
  const result = await request('user/login', {
    method: 'post',
    data: params,
    contentType: 'json',
  });

  return result;
}

async function addEntry(token) {
  const params = {
    //'username': "test12",
      token: token,
      name: "Cat's food",
      amount: 1000,
      type: "EXPENSE"
  }
  const result = await request('entries/add', {
    method: 'post',
    data: params,
    contentType: 'json',
  });

  return result;
}

// This is a route to add new users
routerInstance.get(
    '/test',
    
    async (req,res,next) => {

    try {
        //const response = await userRegister();
        var response = await userLogin();
        const token = response.data.data.token;

        response = await addEntry(token);
        
        const result = {
          'url': response.config.url,
          'data': response.data
        }
        req.log.info(result);
        res.status(201);
        res.json(result);
    }
    catch(e){
        next(new BadRequestError('Couldn\'t create user'));
    }
});

module.exports = routerInstance;